import { Controller, Get, Param, Response } from "@nestjs/common";
import { PrismaClient } from "@prisma/client";
import { WebResult } from "src/common/web.result";
import { FastifyReply } from "fastify";
import { md5 } from "js-md5";

@Controller("avatar")
export class AvatarController {
  constructor(private readonly prisma: PrismaClient) {}

  getCRAvatarURL(email: string): string {
    if (!email) return null;
    const address = email.trim().toLowerCase();
    const addressMD5 = md5(address);
    return `https://cravatar.cn/avatar/${addressMD5}.png?s=200&d=mp`;
  }

  getQQAvatarByEmailOrQQ(email: string): string | never {
    if (
      /^[1-9][0-9]{4,10}$/.test(email) ||
      /^[1-9][0-9]{4,10}@qq.com$/i.test(email)
    ) {
      const qqNum = email.replace(/@qq.com/gi, "");
      return `https://thirdqq.qlogo.cn/g?b=sdk&nk=${qqNum}&s=140`;
    }
    return null;
  }

  @Get("/qq/:qq")
  async getAvatarByQQ(
    @Response() response: FastifyReply,
    @Param("qq") qq: string,
  ) {
    const qqAvatarURL = this.getQQAvatarByEmailOrQQ(qq);
    if (qqAvatarURL) {
      response.redirect(qqAvatarURL, 302);
      return;
    }
    response.redirect(302, "/images/image.default.png");
  }

  @Get(["/email/:email", "/mail/:email"])
  async getAvatarByEmail(
    @Response() response: FastifyReply,
    @Param("email") email: string,
  ) {
    const qqAvatarURL = this.getQQAvatarByEmailOrQQ(email);
    if (qqAvatarURL) {
      response.redirect(302, qqAvatarURL);
      return;
    }

    const cravatarURL = this.getCRAvatarURL(email);
    if (cravatarURL) {
      response.redirect(302, cravatarURL);
      return;
    }
    response.redirect(302, "/images/image.default.png");
  }

  @Get(["/:uid", "/user/:uid"])
  async getAvatar(
    @Response() response: FastifyReply,
    @Param("uid") uid: string,
  ) {
    try {
      const uidNumber = parseInt(uid);
      if (isNaN(uidNumber)) {
        return WebResult.failure(undefined, "id is not a number");
      }
      const user = await this.prisma.user.findUnique({
        select: {
          avatar: true,
          email: true,
        },
        where: {
          id: uidNumber,
        },
      });
      if (!user) {
        response.send(WebResult.failure(undefined, "用户不存在"));
        return;
      }
      // 没有头像，获取 QQAvatar 和 CRAvatar
      console.log(user.avatar);
      if (!user.avatar) {
        const qqAvatarURL = this.getQQAvatarByEmailOrQQ(user.email);
        if (qqAvatarURL) {
          response.redirect(302, qqAvatarURL);
          return;
        }

        const cravatarURL = this.getCRAvatarURL(user.email);
        if (cravatarURL) {
          response.redirect(302, cravatarURL);
          return;
        }
        response.redirect(302, "/images/image.default.png");
        return;
      }

      // 图片链接
      if (user.avatar.includes("/resource")) {
        response.redirect(302, user.avatar);
      }
      // base64 图像数据
      else if (user.avatar.includes("data:image")) {
        response.send(user.avatar);
      }
      // 不知什么数据
      else {
        response.redirect(302, "/images/image.default.png");
      }
    } catch (e) {
      console.error(e);
      response.status(500).send(WebResult.failure(undefined, "内部错误"));
    }
  }

  @Get("/cravatar/:uid")
  async getCRAvatar(
    @Response() response: FastifyReply,
    @Param("uid") uid: string,
  ) {
    try {
      const uidNumber = parseInt(uid);
      if (isNaN(uidNumber)) {
        return WebResult.failure(undefined, "id is not a number");
      }
      const user = await this.prisma.user.findUnique({
        select: {
          email: true,
        },
        where: {
          id: uidNumber,
        },
      });
      if (!user) {
        response.send(WebResult.failure(undefined, "用户不存在"));
      } else if (!user.email) {
        response.redirect(302, "/images/image.default.png");
      }
      const avatarURL = this.getCRAvatarURL(user.email);
      response.redirect(302, avatarURL);
    } catch (e) {
      console.error(e);
      response.status(500).send(WebResult.failure(undefined, "内部错误"));
    }
  }
}
